<?php
class ArticlesController extends AppController {
    var $uses = array('Article', 'ArticleComment', 'ArticleCategory');
    var $paginate = array(
            'limit' => 10,
            'order' => array(
                'Article.id' => 'desc'
            )
        );
    public function index() {
        $this->set("articles", $this->paginate('Article'));
    }

    public function show($id, $title) {
        $result = $this->Article->findById($id);
        $comments = $this->ArticleComment->findAllByArticleId($id);
        $this->title = $result['Article']['title']." - Artykuły";
        $this->set("article", $result);
        $this->set("comments", $comments);
    }

    public function save_comment() {
        if (empty($this->data)) {
            $this->trigger404();
        } else {
            $this->data['ArticleComment']['timestamp'] = time();
            if ($this->ArticleComment->save($this->data)) {
                $this->Article->notifyModelDataChanged();
                $this->Session->setFlash('Zapisano komentarz.');
                $this->redirect(array('action' => 'show', $this->data['ArticleComment']['article_id'], "comment"));
            }
        }
    }
    
    public function admin_index() {
        $this->set("articles", $this->paginate('Article'));
    }

    public function admin_create() {
        $this->title = "Nowy artykuł";

        $this->_prepare_categories();

        $this->helpers[] = "CKEditor";
        if (!empty($this->data)) {
            if ($this->Article->save($this->data)) {
                $this->Session->setFlash('Zapisano artykuł.');
                $this->redirect(array('action' => 'index'));
            }
        }
    }

    public function admin_edit($id) {
        $this->helpers[] = "CKEditor";
        $this->title = "Edycja artykułu";

        $this->_prepare_categories();

        $this->Article->id = $id;
        if (empty($this->data)) {
            $this->data = $this->Article->read();
        } else {
            if ($this->Article->save($this->data)) {
                $this->Session->setFlash('Zapisano artykuł.');
                $this->redirect(array('action' => 'edit', $id));
            }
        }
    }

    public function admin_view($id) {
        $result = $this->Article->findById($id);
        $this->title = "Edycja: " . $result['Article']['title'];
        $this->set("data", $result['Article']);
    }

    private function _prepare_categories() {
        $categories = $this->ArticleCategory->find('all', array('recursive' => -1));
        $finalCategories = array();

        foreach($categories as $category) {
            $finalCategories[$category['ArticleCategory']['id']] = $category['ArticleCategory']['name'];
        }

        $this->set('categories', $finalCategories);
    }
}
?>
